package com.itheima.log;

import com.itheima.utils.DateUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
@Aspect
public class LogAdvice {
    @Autowired
    private HttpServletRequest request;
    @Pointcut("execution(* com.itheima.controller.*.*(..))")
    public void myPoint(){}

    @Around(value = "myPoint()")
    public Object aroundLog(ProceedingJoinPoint pjp) throws Exception {
        Date date = new Date();
        if (request!=null){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            System.out.println(simpleDateFormat.format(date));
            System.out.println(request.getRequestURL());
            System.out.println(request.getRequestURI());
            System.out.println(request.getRemoteAddr());
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            System.out.println(user.getUsername());
        }

        try {

            // 调用切入点方法
            Object rtValue = pjp.proceed();
            // 后置

            return rtValue;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            // 异常

            throw new Exception();
        }finally {
            // 最终
            System.out.println(new Date().getTime() - date.getTime());
        }
    }
}
